package com.jinbai.searcher.web.search_web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Locale;

@Slf4j
@Component
public class DescBuilder {
	private final String lue = "...";

	public String buildOne(String query, Document document, int len) {
		String content = document.getContent().toLowerCase();
		int i = content.indexOf(query);
		if (i == -1) {
			// 说明倒排索引创建的有问题
			log.error("docId = {} 中不包含 {}", document.getDocId(), query);
			return "";
		}

		// 策略：前面截120字，后面截120字 <= 241
		int from = Math.max(i - len, 0);
		int to = Math.min(i + len, content.length());

		String desc = content.substring(from, to);
		desc = desc.replace(query , "<i>" + query + "</i>"); // 高亮显示所查询的词语
		return desc;
	}

	public Document buildList(List<String> wordList, Document doc) {
		StringBuilder allDesc = new StringBuilder();
		allDesc.append(lue);
		int len = Math.max(10, 240 / wordList.size());

		for (String query : wordList) {
			allDesc.append(buildOne(query, doc, len)).append(lue);
		}
		doc.setDesc(allDesc.toString());
		return doc;
	}
}
